/**
 * 核心积分计算逻辑，负责纯数据运算，供主线程与 Web Worker 复用
 * @param {Object} params
 * @param {Array} params.players
 * @param {Array} params.messages
 * @param {string|null} params.winTeam
 * @param {number} params.pointPool
 * @param {string} params.gameName
 * @param {boolean} params.isSettlementMode
 * @returns {{ playersWithScores: Array, serverPayload: { playersForServer: Array, gameInfo: Object, sortedMessages: Array } | null }}
 */
export function calculatePlayerScoresCore({
    players = [],
    messages = [],
    winTeam,
    pointPool = 0,
    gameName = '游戏',
    isSettlementMode = false
} = {}) {
    const safePlayers = Array.isArray(players) ? players : [];
    const safeMessages = Array.isArray(messages) ? messages : [];

    if (safeMessages.length === 0) {
        return { playersWithScores: [], serverPayload: null };
    }

    if (pointPool === 0) {
        const playersWithScores = safePlayers.map(player => ({
            ...player,
            finalScore: 0,
            isWinner: winTeam ? (player.team === winTeam) : false
        }));
        return { playersWithScores, serverPayload: null };
    }

    const safeNumericProduct = (value, multiplier) => Number(value || 0) * Number(multiplier || 0);

    const redTeamTotalGifts = safeMessages
        .filter(msg => msg.team === 'red')
        .reduce((total, msg) => total + safeNumericProduct(msg.gift_point, msg.gift_count), 0);

    const blueTeamTotalGifts = safeMessages
        .filter(msg => msg.team === 'blue')
        .reduce((total, msg) => total + safeNumericProduct(msg.gift_point, msg.gift_count), 0);

    let redPoolShare = 0;
    let bluePoolShare = 0;

    if (winTeam === 'red') {
        redPoolShare = pointPool * 0.7;
        bluePoolShare = pointPool * 0.3;
    } else if (winTeam === 'blue') {
        redPoolShare = pointPool * 0.3;
        bluePoolShare = pointPool * 0.7;
    } else {
        redPoolShare = pointPool * 0.5;
        bluePoolShare = pointPool * 0.5;
    }

    const sumPlayerGifts = (playerId, team) => safeMessages
        .filter(msg => msg.player_id === playerId && msg.team === team)
        .reduce((total, msg) => total + safeNumericProduct(msg.gift_point, msg.gift_count), 0);

    const playersWithTempScores = safePlayers.map(player => {
        const redPlayerGifts = sumPlayerGifts(player.player_id, 'red');
        const bluePlayerGifts = sumPlayerGifts(player.player_id, 'blue');

        let redShare = 0;
        let blueShare = 0;

        if (redTeamTotalGifts > 0 && redPlayerGifts > 0) {
            const redContributionRatio = redPlayerGifts / redTeamTotalGifts;
            redShare = redPoolShare * redContributionRatio;
        }

        if (blueTeamTotalGifts > 0 && bluePlayerGifts > 0) {
            const blueContributionRatio = bluePlayerGifts / blueTeamTotalGifts;
            blueShare = bluePoolShare * blueContributionRatio;
        }

        return {
            ...player,
            redShare,
            blueShare,
            isWinner: winTeam ? (player.team === winTeam) : false
        };
    });

    playersWithTempScores.forEach(player => {
        player.finalRedShare = Math.round(player.redShare || 0);
        player.finalBlueShare = Math.round(player.blueShare || 0);
        const redFinal = player.finalRedShare || 0;
        const blueFinal = player.finalBlueShare || 0;
        player.finalScore = redFinal + blueFinal;
    });

    let serverPayload = null;
    if (isSettlementMode) {
        const playersForServer = playersWithTempScores.map(player => {
            const redPlayerGifts = sumPlayerGifts(player.player_id, 'red');
            const bluePlayerGifts = sumPlayerGifts(player.player_id, 'blue');

            const redContributionRatio = redTeamTotalGifts > 0 ? redPlayerGifts / redTeamTotalGifts : 0;
            const blueContributionRatio = blueTeamTotalGifts > 0 ? bluePlayerGifts / blueTeamTotalGifts : 0;

            return {
                ...player,
                redContributionRatio,
                blueContributionRatio,
                redPlayerGifts,
                bluePlayerGifts
            };
        });

        const gameUuid = safeMessages.length > 0 ? safeMessages[0].uuid : null;

        const gameInfo = {
            uuid: gameUuid,
            winTeam: winTeam || 'draw',
            gameName,
            redTeamTotalGifts,
            blueTeamTotalGifts,
            pointPool,
            redPoolShare,
            bluePoolShare
        };

        const sortedMessages = [...safeMessages].sort((a, b) => {
            if (a.player_id !== b.player_id) {
                return String(a.player_id).localeCompare(String(b.player_id));
            }
            return String(a.team).localeCompare(String(b.team));
        });

        serverPayload = {
            playersForServer,
            gameInfo,
            sortedMessages
        };
    }

    return {
        playersWithScores: playersWithTempScores,
        serverPayload
    };
}
